<?php
	//autolevel
	function getLevelInfo($level)
	{
		$q = mysql_query("SELECT * FROM xp_table WHERE level='$level'");
		return mysql_fetch_array($q);	
	}

	if(isset($_SESSION['user']))
	{
		$aid = $_SESSION['uid'];
		$cid = $_SESSION['cid'];

		$xp = getCharCurrXP($aid);
		$level = getCharLevel($aid);

		$info = getLevelInfo($level);

		$needed = $info['neededxp'];

		$newxp = $xp-$needed;

		$pollars = getPollars($aid);
		$pollars = $pollars+$info['reward'];

		$q = mysql_query("SELECT * FROM xp_table ORDER BY level DESC LIMIT 1");
		$f = mysql_fetch_array($q);

		$charinfo = allCharInfo($cid);

		if($level < $f['level'])
		{
			if($xp >= $needed)
			{
				$level = $level+1;

				$randEnergy = rand(5, 10);
				$randAttack = rand(10, 30);
				$randDefence = rand(7, 27);
				$randHP = rand(10, 20);

				$newEnergy = $charinfo['max energy']+$randEnergy;
				$newAttack = $charinfo['attack']+$randAttack;
				$newDefence = $charinfo['defence']+$randDefence;
				$newHP = $charinfo['max hp']+$randHP;


				if(mysql_query("UPDATE characters SET level='$level', xp='$newxp', `max hp`='$newHP', `max energy`='$newEnergy', attack='$newAttack', defence='$newDefence' WHERE aid='$aid'")or die(alert(mysql_error())))
				{
					if(mysql_query("UPDATE account SET pollars='$pollars' WHERE id='$aid'")or die(mysql_error()))
					{
						alert("Congratulations, you have leveled up! You are now level $level and you earned ".$info['reward']." pollars!");
						redirect(getUrl());
					}
				}
			}
		}
	}
?>